package com.xuecheng.order.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.order.config.PayTemplate;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mapper.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 订单支付信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-09-23
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private PayTemplate payTemplate;
    @Override
    public ResponseResult getPayURL(String orderNo) {
        //1.查询订单
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders ::getOrderNo,orderNo);
        Orders orders = ordersService.getOne(qw);
        //检验是否是初始订单
        if (!orders.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //3.查询订单明细
        LambdaQueryWrapper<Payment> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(Payment ::getOrderNo,orderNo);
        Payment payment = this.getOne(qw2);
        if (payment != null) {
            return ResponseResult.okResult(payment.getPayResponse());
        }
        //3-2.生成支链接 参数：订单号-价格(float)-订单头(文字信息)
        String payUrl = payTemplate.createOrder(orderNo, 1L, orders.getCoursePubName());
        //3-3 封装订单明细
        payment = new Payment();
        payment.setUserId(orders.getUserId());
        payment.setCompanyId(orders.getCompanyId());
        payment.setOrderNo(orders.getOrderNo());
        payment.setPayMethod(OrdersConstants.PAY_METHOD_WX);
        payment.setTotalAmount(orders.getPrice());
        payment.setStatus(OrdersConstants.NOT_PAID.toString()); // 未支付-0;已支付-2；
        payment.setCreateDate(new Date());
        payment.setPayResponse(payUrl);
        //保存到数据库
        this.save(payment);

        //返回支付链接
        return ResponseResult.okResult(payUrl);
    }
}
